package com.profgj.profgj.controller;

import com.profgj.profgj.entity.Unit;
import com.profgj.profgj.enums.ServerStatus;
import com.profgj.profgj.service.UnitService;
import com.profgj.profgj.utils.EmptyUtils;
import com.profgj.profgj.utils.ReturnOperator;
import com.profgj.profgj.validater.UnitValidator;
import com.profgj.profgj.vo.EmptyObject;
import com.profgj.profgj.vo.ResultMsg;
import com.profgj.profgj.vo.ReturnResult;
import io.swagger.annotations.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * (计量单位管理)表控制层
 *
 * @author 杨帅
 * @since 2021-06-22 11:09:35
 */

/**
 * JSON格式返回
 */
@RestController
/**
 * 请求基路径
 */
@RequestMapping("/uit")
@Api(tags = {"计量单位管理"},description = "计量单位管理")
public class UnitController {

    /**
     * 返回空对象的替代品
     */
    private EmptyObject emptyObject = new EmptyObject();


    /**
     * 计量单位服务对象
     */
    @Resource
    private UnitService unitService;


    /**
     * 初始化设置校验器
     * @param binder    校验器绑定对象
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.setValidator(new UnitValidator());
    }


    /**
     * id查询计量单位
     * @param id    计量单位id
     * @return
     */
    @GetMapping("/unit/{id}")
    @ApiOperation(value = "id查询计量单位",produces = "application/json",consumes = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "计量单位id", required = true, dataType = "Integer", paramType = "Integer", dataTypeClass = Integer.class),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "表明该请求被成功地完成,所请求的资源发送到客户端"),
            @ApiResponse(code = 401, message = "请求要求身份验证,常见于需要登录而用户未登录的情况"),
            @ApiResponse(code = 403, message = "服务器拒绝请求,常见于机密信息或复制其它登录而用户未登录的情况"),
            @ApiResponse(code = 404, message = "服务器无法取得所请求的网页,请求资源不存在"),
            @ApiResponse(code = 500, message = "服务器内部错误")
    })
    public ResponseEntity<ResultMsg> unitQueryByIdMethod(@PathVariable("id") Integer id){

        // id校验
        if (!EmptyUtils.isIntegerEmpty(id)) {
            return ReturnOperator.createResultMsg("", ServerStatus.ID_NOT_NULL, ServerStatus.ERROR,
                    new ArrayList<>(), emptyObject, HttpStatus.OK);
        }

        // 查询后的计量单位校验
        Unit unit = unitService.queryById(id);
        if (!EmptyUtils.isUnitEmpty(unit)){
            return ReturnOperator.createResultMsg("", ServerStatus.UNIT_NOT_EXISTS, ServerStatus.ERROR,
                    new ArrayList<>(), emptyObject, HttpStatus.OK);
        }

        // 返回数据
        return ReturnOperator.createResultMsg(ServerStatus.QUERY_MESSAGE_SUCCESS, "", ServerStatus.OK,
                new ArrayList<>(), unit, HttpStatus.OK);


    }


    /**
     * 查询计量单位列表
     * @param draw  绘制次数
     * @param start 查询起始
     * @param length    查询条数
     * @return
     */
    @GetMapping("/unit/list")
    @ApiOperation(value = "查询计量单位列表",produces = "application/json",consumes = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "draw",value = "绘制次数", required = true, dataType = "Integer", paramType = "Integer", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "start",value = "查询起始", required = true, dataType = "Integer", paramType = "Integer", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "length",value = "查询条数", required = true, dataType = "Integer", paramType = "Integer", dataTypeClass = Integer.class),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "表明该请求被成功地完成,所请求的资源发送到客户端"),
            @ApiResponse(code = 401, message = "请求要求身份验证,常见于需要登录而用户未登录的情况"),
            @ApiResponse(code = 403, message = "服务器拒绝请求,常见于机密信息或复制其它登录而用户未登录的情况"),
            @ApiResponse(code = 404, message = "服务器无法取得所请求的网页,请求资源不存在"),
            @ApiResponse(code = 500, message = "服务器内部错误")
    })
    public ResponseEntity<ReturnResult> unitQueryListMethod(Integer draw,
                                                             Integer start,
                                                             Integer length){

        // 参数校验
        if (!EmptyUtils.isIntegerEmpty(start) && !EmptyUtils.isIntegerEmpty(length)) {
            return ReturnOperator.createResultMsg(draw, 0, 0,
                    new ArrayList(), HttpStatus.OK);
        }

        // 得到总记录数
        Integer totalCount = unitService.queryAll().size();
        // 分页查询计量单位
        List<Unit> units = unitService.queryAllByLimit(start,length);

        // 查询结果校验
        if (!EmptyUtils.isUnitListEmpty(units)) {
            return ReturnOperator.createResultMsg(draw, 0, 0,
                    new ArrayList<>(), HttpStatus.OK);
        }

        // 返回数据
        return ReturnOperator.createResultMsg(draw, totalCount, totalCount,
                units, HttpStatus.OK);
    }

    /**
     * 计量单位添加
     * @return
     */
    @PostMapping("/unit")
    @ApiOperation(value = "计量单位添加",produces = "application/json",consumes = "application/json")
    @ApiResponses({
            @ApiResponse(code = 200, message = "表明该请求被成功地完成,所请求的资源发送到客户端"),
            @ApiResponse(code = 401, message = "请求要求身份验证,常见于需要登录而用户未登录的情况"),
            @ApiResponse(code = 403, message = "服务器拒绝请求,常见于机密信息或复制其它登录而用户未登录的情况"),
            @ApiResponse(code = 404, message = "服务器无法取得所请求的网页,请求资源不存在"),
            @ApiResponse(code = 500, message = "服务器内部错误")
    })
    public ResponseEntity<ResultMsg> unitAddMethod(@Valid @RequestBody Unit unit, @ApiIgnore Errors errors,@ApiIgnore HttpSession session){

        // 对象参数校验
        if (errors.hasErrors()) {
            List<ObjectError> oes = errors.getAllErrors();
            for (ObjectError oe : oes) {
                if (oe instanceof FieldError) {
                    FieldError fe = (FieldError) oe;
                    return ReturnOperator.createResultMsg("", fe.getDefaultMessage(), ServerStatus.ERROR,
                            new ArrayList(), emptyObject, HttpStatus.OK);
                } else {
                    return ReturnOperator.createResultMsg("", oe.getDefaultMessage(), ServerStatus.ERROR,
                            new ArrayList(), emptyObject, HttpStatus.OK);
                }
            }
        }

        // 插入数据库计量单位
        Unit unit_new = unitService.insert(unit);

        // 插入数据以后的结果校验
        if (!EmptyUtils.isUnitEmpty(unit_new)) {
            return ReturnOperator.createResultMsg("", ServerStatus.DATA_INSERT_ERR, ServerStatus.ERROR,
                    new ArrayList(), emptyObject, HttpStatus.OK);
        }

        // 返回数据
        return ReturnOperator.createResultMsg(ServerStatus.DATA_INSERT_SUCCESS, "", ServerStatus.OK,
                new ArrayList(), unit_new, HttpStatus.OK);
    }


    /**
     * 计量单位修改
     * @return
     */
    @PutMapping("/unit")
    @ApiOperation(value = "计量单位修改",produces = "application/json",consumes = "application/json")
    @ApiResponses({
            @ApiResponse(code = 200, message = "表明该请求被成功地完成,所请求的资源发送到客户端"),
            @ApiResponse(code = 401, message = "请求要求身份验证,常见于需要登录而用户未登录的情况"),
            @ApiResponse(code = 403, message = "服务器拒绝请求,常见于机密信息或复制其它登录而用户未登录的情况"),
            @ApiResponse(code = 404, message = "服务器无法取得所请求的网页,请求资源不存在"),
            @ApiResponse(code = 500, message = "服务器内部错误")
    })
    public ResponseEntity<ResultMsg> unitChangeByIdMethod(@Valid @RequestBody Unit unit,@ApiIgnore Errors errors,@ApiIgnore HttpSession session){

        // 对象参数校验
        if (errors.hasErrors()) {
            List<ObjectError> oes = errors.getAllErrors();
            for (ObjectError oe : oes) {
                if (oe instanceof FieldError) {
                    FieldError fe = (FieldError) oe;
                    return ReturnOperator.createResultMsg("", fe.getDefaultMessage(), ServerStatus.ERROR,
                            new ArrayList(), emptyObject, HttpStatus.OK);
                } else {
                    return ReturnOperator.createResultMsg("", oe.getDefaultMessage(), ServerStatus.ERROR,
                            new ArrayList(), emptyObject, HttpStatus.OK);
                }
            }
        }

        // 判断哪个没空 就更新哪个
        if (!EmptyUtils.isIntegerEmpty(unit.getId())) {
            return ReturnOperator.createResultMsg("", ServerStatus.ID_NOT_NULL, ServerStatus.ERROR,
                    new ArrayList(), emptyObject, HttpStatus.OK);
        }
        // 插入数据库计量单位
        Unit unit_new = unitService.update(unit);

        // 更新数据以后的结果校验
        if (!EmptyUtils.isUnitEmpty(unit_new)) {
            return ReturnOperator.createResultMsg("", ServerStatus.DATA_UPDATE_ERR, ServerStatus.ERROR,
                    new ArrayList(), emptyObject, HttpStatus.OK);
        }

        // 返回数据
        return ReturnOperator.createResultMsg(ServerStatus.DATA_UPDATE_SUCCESS, "", ServerStatus.OK,
                new ArrayList(), unit_new, HttpStatus.OK);


    }


    /**
     * id计量单位删除
     * @return
     */
    @DeleteMapping("/unit/{id}")
    @ApiOperation(value = "id计量单位删除",produces = "application/json",consumes = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "计量单位id", required = true, dataType = "Integer", paramType = "Integer", dataTypeClass = Integer.class),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "表明该请求被成功地完成,所请求的资源发送到客户端"),
            @ApiResponse(code = 401, message = "请求要求身份验证,常见于需要登录而用户未登录的情况"),
            @ApiResponse(code = 403, message = "服务器拒绝请求,常见于机密信息或复制其它登录而用户未登录的情况"),
            @ApiResponse(code = 404, message = "服务器无法取得所请求的网页,请求资源不存在"),
            @ApiResponse(code = 500, message = "服务器内部错误")
    })
    public ResponseEntity<ResultMsg> unitDeleteByIdMethod(@PathVariable("id") Integer id,@ApiIgnore HttpSession session){

        // id参数校验
        if (!EmptyUtils.isIntegerEmpty(id)) {
            return ReturnOperator.createResultMsg("", ServerStatus.ID_NOT_NULL, ServerStatus.ERROR,
                    new ArrayList(), emptyObject, HttpStatus.OK);
        }

        // 删除失败情况下
        if (!unitService.deleteById(id)) {
            return ReturnOperator.createResultMsg("", ServerStatus.DATA_DELETE_ERR, ServerStatus.ERROR,
                    new ArrayList(), emptyObject, HttpStatus.OK);
        }

        // 返回数据
        return ReturnOperator.createResultMsg(ServerStatus.DATA_DELETE_SUCCESS, "", ServerStatus.OK,
                new ArrayList(), new Boolean(true), HttpStatus.OK);
    }
}
